package com.demo.serializer;

import java.io.IOException;
import java.lang.reflect.Type;

import org.nustaq.serialization.FSTConfiguration;
import org.nustaq.serialization.FSTObjectOutput;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * FST序列化
 *
 */
public class FSTSerializer implements ISerializer {
	//初始化logger
	private static final Logger logger = LoggerFactory.getLogger(FSTSerializer.class);
	//初始化FSTSerializer实例
	private static FSTSerializer instance = new FSTSerializer();
	//初始化FSTConfiguration
	private static final FSTConfiguration fst = FSTConfiguration.createUnsafeBinaryConfiguration();

    /**
     * 无参构造
     */
    private FSTSerializer() {

    }

    /**
     * 获取实例
     * @return
     */
    public static synchronized FSTSerializer getInstance() {
    	if (null == instance) {
    		instance = new FSTSerializer();
    	}
    	
        return instance;
    }

    /**
     * Object转为byteArray
     * @param object
     * @return
     */
    @Override
    public byte[] toByteArray(Object object) {
        FSTObjectOutput fstout = fst.getObjectOutput();
        try {
            fstout.writeObject(object);
            fstout.flush();
        } catch (IOException e) {
            throw new RuntimeException("", e);
        }
        return fstout.getBuffer();
    }
    /**
     * byte[] 转为Object
     * @param bytes
     * @param clazz
     * @return
     */
    @SuppressWarnings("unchecked")
    @Override
    public <T> T toObject(byte[] bytes, Class<T> clazz) {
        T event = null;
        try {
            event = (T) fst.getObjectInput(bytes).readObject();
        } catch (ClassNotFoundException | IOException e) {
        	logger.error("fst serializer toObject error: " + e);
            throw new RuntimeException("", e);
        }
        return event;
    }
    /**
     * 获取type
     * @return
     */
    @Override
    public SerializerType getType() {
        return SerializerType.FST;
    }
    /**
     * byte[] 转为Object
     * @param bytes
     * @param type
     * @return
     */
	@Override
	public <T> T toObject(byte[] bytes, Type type) {
		return null;
	}
}
